/**
 * 
 */
package org.newdawn.yapgame;

import java.util.Iterator;
import java.util.LinkedList;

/**
 * @author Marko Walther
 */
public class ProcessManager implements IProcessManager 
{
	protected LinkedList<Process> procs = new LinkedList<Process>();
	protected LinkedList<Process> nextprocs = new LinkedList<Process>();
	
	public ProcessManager()
	{		
	}
	
	@Override
	public void add(Process process) 
	{
		procs.addLast( process );
		process.onStart();
	}

	@Override
	public void handleProcesses(long delta) 
	{
		Iterator<Process> i = this.procs.iterator();		
		while( i.hasNext() )
		{
			Process p = i.next();
			if( p.isTerminated() )
			{
				Process next = p.getNext();				
				p.onTerminate();
				i.remove();
				if( next != null )
				{
					nextprocs.addLast( next );
					next.onStart();
				}
			}
			else
			{
				p.execute( delta );
			}
		}
		procs.addAll( nextprocs );
		nextprocs.clear();
	}

	@Override
	public void remove(Process process) 
	{
		if( this.procs.contains( process ) )
		{
			this.procs.remove( process );
			if( !process.isTerminated() )
			{
				process.onTerminate();
				process.terminate();
			}
		}
	}

	@Override
	public void removeAll() 
	{
		while( !this.procs.isEmpty() )
		{
			Process process = this.procs.getLast();
			this.procs.remove( process );
			if( !process.isTerminated() )
			{
				process.onTerminate();
				process.terminate();
			}
		}
	}
}
